import modelTemplatesConfig from '@/config/model-templates.json';
import { ModelTemplate, SuggestedModel } from '@/types/model-config';

export interface ProviderTemplate {
  id: string;
  name: string;
  description: string;
  defaultBaseUrl: string;
  alternativeUrls?: string[];
  authType: 'bearer' | 'apikey' | 'oauth' | 'custom';
  headerName?: string;
  headerPrefix?: string;
  models: ModelInfo[];
}

export interface ModelInfo extends SuggestedModel {
  contextWindow?: number;
  pricing?: {
    input: number;
    output: number;
  };
}

export interface ModelDiscoveryConfig {
  endpoint: string;
  method: 'GET' | 'POST';
  headers?: Record<string, string>;
  parseResponse: (response: any) => ModelInfo[];
}

class ModelTemplateService {
  private templates: Map<string, ProviderTemplate>;
  private customTemplates: Map<string, ProviderTemplate>;
  private remoteTemplateUrl: string;
  private updateCheckInterval: number = 24 * 60 * 60 * 1000; // 24小时
  private lastUpdateCheck: Date | null = null;

  constructor() {
    this.templates = new Map();
    this.customTemplates = new Map();
    this.remoteTemplateUrl = import.meta.env.VITE_TEMPLATE_URL || import.meta.env.REACT_APP_TEMPLATE_URL || 
                            'https://api.example.com/model-templates';
    
    // 加载本地模板
    this.loadLocalTemplates();
    
    // 加载自定义模板
    this.loadCustomTemplates();
    
    // 检查远程更新
    this.checkForUpdates();
  }

  /**
   * 加载本地模板
   */
  private loadLocalTemplates() {
    modelTemplatesConfig.providers.forEach(provider => {
      this.templates.set(provider.id, provider as ProviderTemplate);
    });
  }

  /**
   * 加载自定义模板
   */
  private loadCustomTemplates() {
    try {
      const customTemplates = localStorage.getItem('custom-model-templates');
      if (customTemplates) {
        const templates = JSON.parse(customTemplates);
        Object.entries(templates).forEach(([id, template]) => {
          this.customTemplates.set(id, template as ProviderTemplate);
        });
      }
    } catch (error) {
      console.error('Failed to load custom templates:', error);
    }
  }

  /**
   * 保存自定义模板
   */
  private saveCustomTemplates() {
    const templates: Record<string, ProviderTemplate> = {};
    this.customTemplates.forEach((template, id) => {
      templates[id] = template;
    });
    localStorage.setItem('custom-model-templates', JSON.stringify(templates));
  }

  /**
   * 获取所有提供商模板
   */
  getAllProviders(): ProviderTemplate[] {
    const allTemplates = [
      ...Array.from(this.templates.values()),
      ...Array.from(this.customTemplates.values())
    ];
    
    return allTemplates.sort((a, b) => {
      // 推荐的提供商排在前面
      const aHasRecommended = a.models.some(m => m.recommended);
      const bHasRecommended = b.models.some(m => m.recommended);
      
      if (aHasRecommended && !bHasRecommended) return -1;
      if (!aHasRecommended && bHasRecommended) return 1;
      
      return a.name.localeCompare(b.name);
    });
  }

  /**
   * 根据ID获取提供商模板
   */
  getProviderById(providerId: string): ProviderTemplate | undefined {
    return this.templates.get(providerId) || this.customTemplates.get(providerId);
  }

  /**
   * 获取提供商的模型列表
   */
  getProviderModels(providerId: string): ModelInfo[] {
    const provider = this.getProviderById(providerId);
    return provider?.models || [];
  }

  /**
   * 搜索模型
   */
  searchModels(query: string): Array<{ provider: ProviderTemplate; model: ModelInfo }> {
    const results: Array<{ provider: ProviderTemplate; model: ModelInfo }> = [];
    const searchTerm = query.toLowerCase();

    this.getAllProviders().forEach(provider => {
      provider.models.forEach(model => {
        if (
          model.name.toLowerCase().includes(searchTerm) ||
          model.displayName.toLowerCase().includes(searchTerm) ||
          model.description.toLowerCase().includes(searchTerm) ||
          model.capabilities?.some(cap => cap.toLowerCase().includes(searchTerm))
        ) {
          results.push({ provider, model });
        }
      });
    });

    return results;
  }

  /**
   * 添加自定义模板
   */
  addCustomTemplate(template: ProviderTemplate): void {
    const id = `custom-${Date.now()}`;
    this.customTemplates.set(id, { ...template, id });
    this.saveCustomTemplates();
  }

  /**
   * 更新自定义模板
   */
  updateCustomTemplate(id: string, template: Partial<ProviderTemplate>): void {
    const existing = this.customTemplates.get(id);
    if (existing) {
      this.customTemplates.set(id, { ...existing, ...template });
      this.saveCustomTemplates();
    }
  }

  /**
   * 删除自定义模板
   */
  deleteCustomTemplate(id: string): void {
    this.customTemplates.delete(id);
    this.saveCustomTemplates();
  }

  /**
   * 添加自定义模型到提供商
   */
  addCustomModel(providerId: string, model: ModelInfo): void {
    const provider = this.customTemplates.get(providerId) || this.templates.get(providerId);
    
    if (provider) {
      // 如果是内置模板，创建一个自定义副本
      if (this.templates.has(providerId)) {
        const customProvider = { ...provider, id: `${providerId}-custom` };
        customProvider.models = [...provider.models, model];
        this.customTemplates.set(customProvider.id, customProvider);
      } else {
        // 如果已经是自定义模板，直接添加
        provider.models.push(model);
        this.customTemplates.set(providerId, provider);
      }
      
      this.saveCustomTemplates();
    }
  }

  /**
   * 自动发现模型（调用提供商API）
   */
  async discoverModels(providerId: string, baseUrl: string, apiKey: string): Promise<ModelInfo[]> {
    const discoveryConfigs: Record<string, ModelDiscoveryConfig> = {
      openai: {
        endpoint: '/models',
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${apiKey}`
        },
        parseResponse: (response) => {
          return response.data?.map((model: any) => ({
            name: model.id,
            displayName: model.id,
            description: `OpenAI model: ${model.id}`,
            capabilities: ['text'],
            maxTokens: model.max_tokens || 4096
          })) || [];
        }
      },
      claude: {
        endpoint: '/models',
        method: 'GET',
        headers: {
          'X-API-Key': apiKey
        },
        parseResponse: (response) => {
          return response.models?.map((model: any) => ({
            name: model.model_id,
            displayName: model.display_name || model.model_id,
            description: model.description || '',
            capabilities: model.capabilities || ['text'],
            maxTokens: model.max_tokens || 4096,
            contextWindow: model.context_window || 100000
          })) || [];
        }
      }
    };

    const config = discoveryConfigs[providerId];
    if (!config) {
      throw new Error(`Model discovery not supported for provider: ${providerId}`);
    }

    try {
      const response = await fetch(`${baseUrl}${config.endpoint}`, {
        method: config.method,
        headers: {
          'Content-Type': 'application/json',
          ...config.headers
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return config.parseResponse(data);
    } catch (error) {
      console.error('Model discovery failed:', error);
      
      // 返回模板中的默认模型
      return this.getProviderModels(providerId);
    }
  }

  /**
   * 检查并更新远程模板
   */
  async checkForUpdates(): Promise<boolean> {
    // 检查是否需要更新
    if (this.lastUpdateCheck) {
      const timeSinceLastCheck = Date.now() - this.lastUpdateCheck.getTime();
      if (timeSinceLastCheck < this.updateCheckInterval) {
        return false;
      }
    }

    try {
      const response = await fetch(this.remoteTemplateUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const remoteTemplates = await response.json();
      
      // 检查版本
      if (remoteTemplates.version > modelTemplatesConfig.version) {
        // 更新本地模板
        this.updateLocalTemplates(remoteTemplates);
        this.lastUpdateCheck = new Date();
        
        // 保存更新信息
        localStorage.setItem('model-templates-version', remoteTemplates.version);
        localStorage.setItem('model-templates-updated', new Date().toISOString());
        
        return true;
      }
    } catch (error) {
      console.error('Failed to check for template updates:', error);
    }

    this.lastUpdateCheck = new Date();
    return false;
  }

  /**
   * 更新本地模板
   */
  private updateLocalTemplates(remoteTemplates: any) {
    // 清空现有模板
    this.templates.clear();
    
    // 加载新模板
    remoteTemplates.providers.forEach((provider: any) => {
      this.templates.set(provider.id, provider as ProviderTemplate);
    });
    
    console.log('Model templates updated successfully');
  }

  /**
   * 获取模型推荐
   */
  getRecommendedModels(): Array<{ provider: ProviderTemplate; model: ModelInfo }> {
    const recommendations: Array<{ provider: ProviderTemplate; model: ModelInfo }> = [];
    
    this.getAllProviders().forEach(provider => {
      provider.models.forEach(model => {
        if (model.recommended) {
          recommendations.push({ provider, model });
        }
      });
    });
    
    return recommendations;
  }

  /**
   * 根据能力筛选模型
   */
  getModelsByCapability(capability: string): Array<{ provider: ProviderTemplate; model: ModelInfo }> {
    const results: Array<{ provider: ProviderTemplate; model: ModelInfo }> = [];
    
    this.getAllProviders().forEach(provider => {
      provider.models.forEach(model => {
        if (model.capabilities?.includes(capability)) {
          results.push({ provider, model });
        }
      });
    });
    
    return results;
  }

  /**
   * 导出模板
   */
  exportTemplates(): string {
    const exportData = {
      version: modelTemplatesConfig.version,
      builtin: Array.from(this.templates.values()),
      custom: Array.from(this.customTemplates.values())
    };
    
    return JSON.stringify(exportData, null, 2);
  }

  /**
   * 导入模板
   */
  importTemplates(data: string): void {
    try {
      const importData = JSON.parse(data);
      
      if (importData.custom) {
        importData.custom.forEach((template: ProviderTemplate) => {
          this.customTemplates.set(template.id, template);
        });
        
        this.saveCustomTemplates();
      }
    } catch (error) {
      console.error('Failed to import templates:', error);
      throw new Error('Invalid template format');
    }
  }

  /**
   * 验证模型配置
   */
  validateModelConfig(providerId: string, modelName: string): boolean {
    const provider = this.getProviderById(providerId);
    if (!provider) return false;
    
    return provider.models.some(m => m.name === modelName);
  }

  /**
   * 获取模型定价信息
   */
  getModelPricing(providerId: string, modelName: string): { input: number; output: number } | undefined {
    const provider = this.getProviderById(providerId);
    const model = provider?.models.find(m => m.name === modelName);
    
    return model?.pricing;
  }
}

export default new ModelTemplateService();